"""
created  by  hzwlxy  at 2018/7/3 11:24
__author__: 西瓜哥
__QQ__ : 120235331
"""
from flask import Flask
from flask_wtf import CSRFProtect

__author__ = '西瓜哥'


def create_app():
    app = Flask(__name__)
    CSRFProtect(app)
    register_database(app)

    from app.ext import db, login_manager
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.session_protection = 'strong'
    login_manager.blueprint_login_views = {
        'user': "user.login",
        'admin': "admin.login",
    }
    register_blueprint(app)
    return app


def register_database(app):
    app.config.from_object('app.config.setting')
    app.config.from_object('app.config.secure')
    app.config['TEMPLATES_AUTO_RELOAD'] = True
    uri = "{dbtype}://{username}:{password}@{host}:{port}/{dbname}".format(
        dbtype=app.config['DB_CONNECTION'], username=app.config['DB_USERNAME'],
        password=app.config['DB_PASSWORD'],
        host=app.config['DB_HOST'], port=app.config['DB_PORT'], dbname=app.config['DB_DATABASE'])

    app.config['SQLALCHEMY_DATABASE_URI'] = uri
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True


def register_blueprint(app):
    from app.web import admin_app, user_app, web_app
    from app.api.v1 import create_blueprint
    app.register_blueprint(web_app)
    app.register_blueprint(user_app, url_prefix="/user")
    app.register_blueprint(admin_app, url_prefix=app.config['ADMIN_PREFIX'])
    app.register_blueprint(create_blueprint())
